package io.renren.modules.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.renren.common.exception.RRException;
import io.renren.common.util.Constant;
import io.renren.config.GlobalConfig;
import io.renren.modules.common.BaseService;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.pojo.SysUserQuery;
import io.renren.modules.sys.pojo.SysUserRoleDTO;
import io.renren.modules.sys.service.SecurityService;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.security.pojo.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
@CacheConfig(cacheNames = GlobalConfig.CACHE_KEY_PREFIX + "sys_user")
public class SysUserServiceImpl extends BaseService
		implements SysUserService {
	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private SecurityService securityService;

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserDao.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserDao.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return sysUserDao.queryByUserName(username);
	}
	
	@Override
	public SysUserEntity queryObject(Long userId) {
		return sysUserDao.queryObject(userId);
	}

	@Override
	public List<SysUserEntity> queryList(SysUserQuery query){
		return sysUserDao.queryList(query);
	}

	@Override
	public PageInfo<SysUserEntity> queryPage(SysUserQuery query) {
		return PageHelper.startPage(query.getPage(),query.getLimit())
				.doSelectPageInfo(() -> sysUserDao.queryList(query));
	}

	@Override
	public long queryTotal(SysUserQuery query) {
		return PageHelper.count(() -> sysUserDao.queryList(query));
	}

	@Override
	@Transactional
	@CacheEvict(key = "#user.username")
	public void save(SysUserRoleDTO user) {
		user.setCreateTime(new Date());
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		sysUserDao.save(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	@CacheEvict(key = "#user.username")
	public void update(SysUserRoleDTO user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(passwordEncoder.encode(user.getPassword()));
		}
		sysUserDao.update(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	@CacheEvict(allEntries = true)
	public void deleteBatch(Long[] userId) {
		sysUserDao.deleteBatch(userId);
	}

	@Override
	@CacheEvict(key = "#user.username")
	public void updatePassword(SysUserEntity user, String password, String newPassword) {
		//加密
		password = passwordEncoder.encode(password);
		newPassword = passwordEncoder.encode(newPassword);

		Map<String, Object> map = new HashMap<>();
		map.put("userId", user.getUserId());
		map.put("password", password);
		map.put("newPassword", newPassword);

		int count = sysUserDao.updatePassword(map);
		if(count == 0){
			throw new RRException("原密码不正确");
		}
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserRoleDTO user){
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
		
		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}

	@Override
	@Cacheable(key = "#username")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//用户信息
		SysUserEntity user = this.queryByUserName(username);

		//账号不存在、密码错误
		if(user == null) {
			throw new RRException("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			throw new RRException("账号已被锁定,请联系管理员");
		}

		Set<GrantedAuthority> authorities = new HashSet<>();
		Set<String> permissions = securityService.getUserPermissions(user.getUserId());
		for(String permission : permissions){
			authorities.add(new SimpleGrantedAuthority(permission));
		}
		return new SecurityUser(user,authorities);
	}
}
